package cn.edu.ahstu.acm.controller.json;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.edu.ahstu.acm.entity.Problem;
import cn.edu.ahstu.acm.entity.User;
import cn.edu.ahstu.acm.mapper.ProblemMapper;
import cn.edu.ahstu.acm.mapper.StatusMapper;
import cn.edu.ahstu.acm.support.CurrentUser;

@Controller
@RequestMapping("/json")
public class ProblemJsonController {

	@Autowired
	private ProblemMapper problemMapper;

	@Autowired
	private StatusMapper statusMapper;

	@RequestMapping("/problemlist/{page}/{pageSize}")
	@ResponseBody
	public List<Problem> findList(@CurrentUser User user, @PathVariable Long page,
			@PathVariable Long pageSize, Model model) {
		Long offset = (page - 1) * pageSize;
		List<Problem> problemList = problemMapper.queryForList(null, offset,
				pageSize);
		if (user != null) {
			for (int i = 0; i < problemList.size(); i++) {
				Problem problem = problemList.get(i);
				Integer result = statusMapper.queryResult(user.getUid(),
						problem.getPid());
				if (result == null) {
					result = 0;
				} else if (result == 0) {
					result = 1;
				} else {
					result = 2;
				}
				problem.setStatus(result);
			}
		}
		model.addAttribute("problemList", problemList);
		model.addAttribute("total", problemMapper.count() / pageSize + 1);
		model.addAttribute("currentPage", page);
		model.addAttribute("pageSize", pageSize);
		return null;
	}

}
